﻿/// <reference path="core/Error.js"/>
/// <reference path="FaScript.js"/>

"use strict";
Namespace('FaScript.WebSocket');

FaScript.WebSocket.defineClass('WebSocket',
	function (host) {
	    var object = Object.create(null);

	    //私有变量
	    var _socket = new WebSocket(host);
	    _socket.onerror = function (errorEvent) {
	        console.error('WebSocket Status:: Error was reported \r\n', errorEvent);
	    };
	    _socket.onopen = function (openEvent) {
	        console.log('WebSocket Status:: Socket Open \r\n', openEvent);
	    };
	    _socket.onmessage = function (messageEvent) {
	        if (_hm != null) {
	            _hm(JSON.parse(messageEvent.data));
	        }

	        console.log('Server Reply:: ' + messageEvent.data + ' \r\n', messageEvent);
	    };
	    _socket.onclose = function (closeEvent) {
	        if (!closeEvent.wasClean) {
	            throw Error.defineError('', 'WebSocket未能正确关闭');
	        }
	        console.log('WebSocket Status:: Socket Closed \r\n', closeEvent);
	    };

	    //属性
	    var _hm = null;
	    Object.defineProperties(object,
            {
                'handMessage': { get: function () { return _hm; }, set: function (fn) { _hm = fn; } }
            });

	    //方法
	    Object.defineProperty(object, 'sendTextMessage', {
	        value: function (value) {
	            /// <summary>发送文本消息</summary>
	            /// <param name="value" type="JSON" >消息内容</param>
	            //if (_socket.readyState != WebSocket.OPEN) return;

	            _socket.send(JSON.stringify(value));
	        }
	    });
	    Object.defineProperty(object, 'sendBinaryMessage', {
	        value: function (value) {
	            /// <summary>发送文本消息</summary>
	            /// <param name="value" type="JSON" >消息内容</param>
	            //if (_socket.readyState != WebSocket.OPEN) return;

	            _socket.send(value);
	        }
	    });

        //锁定成员
	    Object.seal(object);
	    return object;
	});

FaScript.WebSocket.defineEnum('CloseCode', {});